import { ref } from 'vue';

export interface ModalConfig {
  visible: boolean;
  data?: any;
}

// 定义参数类型
type ModalDataParam = any | (() => Promise<any>);

export function useModal(modalCount = 1) {
  const modals = ref<ModalConfig[]>(
    Array(modalCount)
      .fill(null)
      .map(() => ({
        visible: false,
        data: null
      }))
  );

  // 改造 openModal 方法，支持多种参数
  const openModal = async (index: number, ...args: ModalDataParam[]) => {
    if (index >= 0 && index < modals.value.length) {
      try {
        let modalData: any = {};

        // 处理传入的参数
        for (const arg of args) {
          if (typeof arg === 'function') {
            // 如果是函数，执行并获取结果
            const result = await arg();
            modalData = { ...modalData, ...result };
          } else {
            // 如果是普通数据，直接合并
            modalData = { ...modalData, ...(typeof arg === 'object' ? arg : { value: arg }) };
          }
        }

        // 设置数据并打开弹窗
        modals.value[index].data = modalData;
        modals.value[index].visible = true;
      } catch (error) {
        console.error('打开弹窗失败:', error);
      }
    }
  };

  const closeModal = (index: number) => {
    if (index >= 0 && index < modals.value.length) {
      modals.value[index].visible = false;
      modals.value[index].data = null;
    }
  };

  return {
    modals,
    openModal,
    closeModal
  };
}
